import { defineConfig, loadEnv, type ConfigEnv } from "vite";
import { resolve } from "path";

import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
// https://www.npmjs.com/package/vite-easy-mock
import viteMock from "vite-easy-mock";

// https://vitejs.dev/config/
export default defineConfig((mode: ConfigEnv) => {
  const env = loadEnv(mode.mode, process.cwd());

  // console.log(env);

  return {
    plugins: [
      vue(),
      vueJsx(),
      viteMock({
        pattern: "/mock",
        dir: "/",
      }),
    ],
    resolve: {
      // 配置路径别名
      alias: {
        "@": resolve(__dirname, "src"),
      },
      // 配置文件扩展名
      extensions: [".ts", ".vue", ".js", ".jsx", ".tsx"], // 导入时想要省略的扩展名列表。
    },
    css: {
      preprocessorOptions: {
        scss: {
          // 引入 var.scss 这样就可以在全局中使用 var.scss中预定义的变量了
          // 给导入的路径最后加上 ;
          additionalData: '@import "./src/styles/variables.scss";',
        },
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: "internal:charset-removal",
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === "charset") {
                  atRule.remove();
                }
              },
            },
          },
        ],
      },
    },
    // 开发服务器配置
    // https://cn.vitejs.dev/config/server-options.html#server-open
    server: {
      port: +env.VITE_PORT,
      open: Boolean(env.VITE_OPEN),
      // 代理服务器配置
      proxy: {
        "/app-dev": {
          target: "http://gmall-h5-api.atguigu.cn", // 目标服务器地址
          changeOrigin: true, // 允许跨域
          rewrite: (path: string) => path.replace(/^\/app-dev/, ""), // 路径重写
        },
      },
    },
  };
});
